package com.yuhanginfo.modules.web.web;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.yuhanginfo.common.config.Global;
import com.yuhanginfo.common.persistence.Page;
import com.yuhanginfo.common.utils.DateUtils;
import com.yuhanginfo.common.utils.excel.ExportExcel;
import com.yuhanginfo.common.utils.excel.ImportExcel;
import com.yuhanginfo.common.web.BaseController;
import com.yuhanginfo.modules.web.util.WebUserUtils;
import com.yuhanginfo.modules.web.entity.WebAddress;
import com.yuhanginfo.modules.web.entity.WebCredit;
import com.yuhanginfo.modules.web.entity.WebGoods;
import com.yuhanginfo.modules.web.entity.WebInvoice;
import com.yuhanginfo.modules.web.entity.WebInvoiceInfo;
import com.yuhanginfo.modules.web.entity.WebOrders;
import com.yuhanginfo.modules.web.entity.WebOrdersDetail;
import com.yuhanginfo.modules.web.entity.WebWaybill;
import com.yuhanginfo.modules.web.entity.WebYongUser;
import com.yuhanginfo.modules.web.entity.WebExportOrder;
import com.yuhanginfo.modules.web.service.AddressService;
import com.yuhanginfo.modules.web.service.OrderService;
import com.yuhanginfo.modules.web.service.WebClassService;
import com.yuhanginfo.modules.web.service.WebCreditService;
import com.yuhanginfo.modules.web.service.WebGoodsService;
import com.yuhanginfo.modules.web.service.WebInvoiceInfoService;
import com.yuhanginfo.modules.web.service.WebInvoiceService;
import com.yuhanginfo.modules.web.service.WebOrdersDetailService;
import com.yuhanginfo.modules.web.service.WebStoreService;
import com.yuhanginfo.modules.web.service.WebWaybillService;

/**
 * 订单管理
 *
 */
@Controller
@RequestMapping(value = "${frontPath}/order")
public class OrderController extends BaseController {
	@Autowired
	private OrderService orderService;
	@Autowired
	private WebStoreService webStoreService;
	@Autowired
	private WebOrdersDetailService webOrdersDetailService;
	@Autowired
	private WebInvoiceInfoService webInvoiceInfoService;
	@Autowired
	private WebWaybillService webWaybillService;
	@Autowired
	private WebClassService webClassService;
	@Autowired
	private WebGoodsService webGoodsService;
	@Autowired
	private WebInvoiceService webInvoiceService;
	@Autowired
	private WebCreditService webCreditService;
	@Autowired
	private AddressService webAddressService;

	// 我的订单列表
	@RequestMapping(value = "myOrder")
	public String myOrder(HttpSession session, HttpServletRequest request, HttpServletResponse response, Model model,
			String createDate, String buyStoreName, String state, String orderCode, String pages) {
		if (WebUserUtils.getYongUser().getId() != null && WebUserUtils.getYongUser().getId() != "") {
			List<WebOrders> storeList = orderService.selectMyStoreList(WebUserUtils.getYongUser().getId());
			WebOrders orders = new WebOrders();
			orders.setUserId(Integer.parseInt(WebUserUtils.getYongUser().getId()));
			if (createDate != null && createDate != "" && !"订单日期筛选".equals(createDate) && createDate.length() > 0) {
				String startDate = createDate.substring(0, 10);
				String endDate = createDate.substring(13, createDate.length());
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				try {
					orders.setStartTime(sdf.parse(startDate + ' ' + "00:00:00"));
					orders.setEndTime(sdf.parse(endDate + ' ' + "23:59:59"));
					model.addAttribute("createDate", createDate);
				} catch (ParseException e) {
					logger.error(e.getMessage(),e);
				}
			}
			if (buyStoreName != null && buyStoreName != "") {
				orders.setBuyStoreName(buyStoreName);
				model.addAttribute("buyStoreName", buyStoreName);
			}
			if (state != null && state != "") {
				orders.setState(state);
				model.addAttribute("status", state);
			}

			if (orderCode != null && orderCode != "") {
				orders.setCode(orderCode);
				model.addAttribute("goodsName", orderCode);
			}
			List<WebOrders> listPhone = orderService.myPhoneList(orders);
			Page<WebOrders> page = orderService.myOrderPage(new Page<WebOrders>(request, response), orders);
			List<WebOrders> list = page.getList();
			model.addAttribute("listPhone", listPhone);
			model.addAttribute("pages", pages);
			model.addAttribute("storeList", storeList);
			model.addAttribute("page", page);
			model.addAttribute("list", list);
			model.addAttribute("allClassesList", webClassService.getAllClasses());
			model.addAttribute("actionCenter", "ord");
			return "modules/web/Order/myOrder";
		} else {
			return "modules/web/webLogin";
		}
	}

	// 待付款订单详情
	@RequestMapping(value = "/orderDetail")
	public String orderDetail(Model model, String ordersCode, String transportType, String id) {
		WebYongUser yongUser = WebUserUtils.getYongUser();
		if (yongUser.getId() == null) {
			return "modules/web/webLogin";
		}
		List<WebOrdersDetail> list = webOrdersDetailService.selectByOrderCode(ordersCode);
		WebOrders orders = orderService.selectById(id);
		WebInvoiceInfo webInvoiceInfo = webInvoiceInfoService.selectByOrdersCode(orders.getCode());
		WebInvoice webInvoi = new WebInvoice();
		webInvoi.setUserId(yongUser.getId());
		List<WebInvoice> webInvoice = webInvoiceService.selectInvoiceByUserId(webInvoi);
		BigDecimal goodsMoney = BigDecimal.valueOf(0.00);
		for (WebOrdersDetail webOrdersDetail : list) {
			if (webOrdersDetail.getFhNum() == null || webOrdersDetail.getFhNum() == "") {
				webOrdersDetail.setFhNum("0");
			}

			Integer num = webOrdersDetail.getNum();
			webOrdersDetail.setTotalMoney(webOrdersDetail.getPrice().multiply(BigDecimal.valueOf(num)));

			BigDecimal to = webOrdersDetail.getPrice().multiply(BigDecimal.valueOf(num));
			goodsMoney = goodsMoney.add(to);
		}
		model.addAttribute("goodsMoney", goodsMoney);
		model.addAttribute("state", list.get(0).getState());
		model.addAttribute("createDate", list.get(0).getCreateDate());
		model.addAttribute("orders", orders);
		model.addAttribute("webInvoiceInfo", webInvoiceInfo);
		model.addAttribute("list", list);
		model.addAttribute("id", id);
		model.addAttribute("ordersCode", ordersCode);
		model.addAttribute("allClassesList", webClassService.getAllClasses());
		if (!webInvoice.isEmpty()) {
			model.addAttribute("invofo", webInvoice.get(0));
		}
		return "modules/web/Order/orderDetail";
	}

	// 取消订单
	@RequestMapping(value = "/cancelOrder")
	public String cancelOrder(String orderId, WebOrders orders) {
		orders.setState("6");
		orders.setId(orderId);
		orders.setUpdateDate(new Date());
		orderService.cancelOrder(orders);
		return "redirect:" + Global.getFrontPath() + "/order/myOrder";
	}

	@RequestMapping(value = "/logisticsSelect")
	public String logisticsSelect(String orderCode, Model model) {
		List<WebWaybill> webWaybill = webWaybillService.selectByOrderCode(orderCode);
		model.addAttribute("webWaybill", webWaybill);
		model.addAttribute("orderCode", orderCode);
		return "modules/web/Order/logisticsSelect";
	}

	// 物流数据
	@ResponseBody
	@RequestMapping(value = "/waybillData")
	public List<WebWaybill> waybillData(String wuCode, String orderCode) {
		return webWaybillService.selectByLogisticsCode(wuCode, orderCode);
	}

	@RequestMapping(value = "/wuInformatin")
	public String wuInformatin(String orderCode, Model model) {
		List<WebWaybill> webWaybill = webWaybillService.selectByOrderCode(orderCode);
		model.addAttribute("webWaybill", webWaybill);
		return "modules/web/Order/wuInformation";
	}

	// 我的订单下拉查询分页
	@RequestMapping(value = "/selectPhoneList")
	public String selectPhoneList(String name, Model model, Integer p, String createDate, String buyStoreName,
			String state, String goodsName) {
		Map<String, Object> map = new HashMap<String, Object>();
		int a = 4 * (p - 1);
		map.put("a", a);
		map.put("name", name);
		map.put("buyStoreName", buyStoreName);
		map.put("state", state);
		map.put("goodsName", goodsName);
		map.put("userId", WebUserUtils.getYongUser().getId());
		if (createDate != null && createDate != "" && !"订单日期筛选".equals(createDate) && createDate.length() > 0) {
			String startDate = createDate.substring(0, 10);
			String endDate = createDate.substring(13, createDate.length());
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			try {
				map.put("startDate", sdf.parse(startDate + ' ' + "00:00:00"));
				map.put("startDate", sdf.parse(endDate + ' ' + "23:59:59"));
			} catch (ParseException e) {
				logger.error(e.getMessage(),e);
			}
		}
		List<WebOrders> list = orderService.selectPhoneList(map);
		model.addAttribute("list", list);
		return "modules/web/Order/myOrderPhone";
	}

	// 快速下单
	@RequestMapping(value = "/fastOrder")
	public String fastOrder(Model model) {
		WebYongUser yongUser = WebUserUtils.getYongUser();
		if ("2".equals(yongUser.getUserType())) {
			model.addAttribute("fastStore", webStoreService.findStoreByUserId(yongUser.getId()));
		} else {
			model.addAttribute("fastStore", webStoreService.storeList());
		}

		return "modules/web/Order/fastOrder";
	}

	// 下载模板
	@RequestMapping(value = "/importFastOrder")
	public void importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = "快速下单导入模板.xlsx";
			List<WebGoods> list = Lists.newArrayList();
			new ExportExcel("", WebGoods.class, 2).setDataList(list).write(response, fileName).dispose();
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			addMessage(redirectAttributes, "导入模板下载失败！失败信息：" + e.getMessage());
		}

	}

	// 导入数据
	@RequestMapping(value = "/uploadOrder")
	public String uploadOrder(MultipartFile file, String storeCode, Model model, HttpSession session, String ppType)
			throws InvalidFormatException, IOException, InstantiationException, IllegalAccessException {
		if (ppType == null || "".equals(ppType)) {
			ppType = "0";
		}
		WebYongUser yongUser = WebUserUtils.getYongUser();
		String fileName = file.getOriginalFilename();
		if (fileName.indexOf("快速下单") != -1) {
			int failureNum = 0;
			String useType = yongUser.getUserType();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<WebGoods> list = ei.getDataList(WebGoods.class);
			List<WebGoods> list0 = new ArrayList<WebGoods>();
			for (WebGoods webGoods : list) {
				WebGoods goods1 = new WebGoods();
				WebGoods goods2 = new WebGoods();
				WebGoods goods3 = new WebGoods();
				Pattern p = Pattern.compile("\\s*|\t|\r|\n");
				Matcher finalGoodsName = p.matcher(webGoods.getCnName());
				Matcher finalPartsCode = p.matcher(webGoods.getPartsCode());
				String parts = finalPartsCode.replaceAll("");
				String useParts;
				if (parts.indexOf('E') != -1) {
					String st = parts.substring(0, parts.indexOf('E'));
					useParts = st.replace(".", "");
				} else {
					useParts = parts;
				}
				webGoods.setPartsCode(useParts);
				goods1.setCnName(finalGoodsName.replaceAll(""));
				goods1.setStoreCode(storeCode);
				// 配件
				if ("0".equals(ppType)) {
					goods2.setPartsCode(useParts);
				}
				// 厂家编号
				if ("1".equals(ppType)) {
					goods2.setVenderCode(useParts);
				}
				// 物料编号
				if ("2".equals(ppType)) {
					goods2.setCode(useParts);
				}
				goods2.setStoreCode(storeCode);

				goods3.setStoreCode(storeCode);
				goods3.setCnName(finalGoodsName.replaceAll(""));
				goods3.setPartsCode(useParts);
				List<WebGoods> partsCode = webGoodsService.fastOrder(goods2);
				if (!partsCode.isEmpty()) {
					webGoods.setFailReason("0");
					for (WebGoods webGoods2 : partsCode) {
						WebGoods webGo = new WebGoods();

						if ("2".equals(useType)) {
							webGo.setPrice(webGoods2.getVipPrice());
						} else {
							webGo.setPrice(webGoods2.getPrice());
						}
						webGo.setCnName(webGoods2.getCnName());
						// 配件
						if ("0".equals(ppType)) {
							webGo.setStu("0");
							webGo.setPartsCode(webGoods2.getPartsCode());

						}
						// 厂家编号
						if ("1".equals(ppType)) {
							webGo.setVenderCode(webGoods2.getVenderCode());
							webGo.setPartsCode(webGoods2.getPartsCode());
							webGo.setStu("1");

						}
						// 物料编号
						if ("2".equals(ppType)) {
							webGo.setCode(webGoods2.getCode());
							webGo.setPartsCode(webGoods2.getPartsCode());
							webGo.setStu("2");
						}

						webGo.setGoodsNum(webGoods.getGoodsNum());
						webGo.setId(webGoods2.getId());
						String st = webGoods2.getImage();
						if (st != null && st != "") {
							webGo.setImage(st.split(";")[0]);
						}
						webGo.setFailReason("0");
						list0.add(webGo);
					}
				} else {
					/*
					 * 0 :成功 1:配件编号匹配失败 2:商品名称匹配失败 3:商品配件与编号不一致
					 *
					 */

					webGoods.setFailReason("1");
					list0.add(webGoods);
					failureNum++;
				}
			}
			model.addAttribute("failureNum", failureNum);
			model.addAttribute("list", list0);
			model.addAttribute("orderLength", list0.size());
			model.addAttribute("ords", 1);
			model.addAttribute("storeCode", storeCode);
			if ("0".equals(ppType)) {
				model.addAttribute("ppTitle", "配件编号");
			}

			if ("1".equals(ppType)) {
				model.addAttribute("ppTitle", "厂家编号");
			}

			if ("2".equals(ppType)) {
				model.addAttribute("ppTitle", "物料编号");
			}
			model.addAttribute("ppType", ppType);
			session.setAttribute("orderList", list0);
		} else {
			model.addAttribute("mess", 1);
		}
		if ("2".equals(yongUser.getUserType())) {
			model.addAttribute("fastStore", webStoreService.findStoreByUserId(WebUserUtils.getYongUser().getId()));
		} else {
			model.addAttribute("fastStore", webStoreService.storeList());
		}
		return "modules/web/Order/fastOrder";

	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/selectFastOrder")
	public String selectFastOrder(String goodsName, Model model, String status, HttpSession session, String failureNum,
			String orderLength, String storeCode) {
		WebYongUser yongUser = WebUserUtils.getYongUser();
		List<WebGoods> list = new ArrayList<WebGoods>();
		List<WebGoods> list1 = new ArrayList<WebGoods>();
		List<WebGoods> list0 = (List<WebGoods>) session.getAttribute("orderList");
		for (WebGoods webGoods : list0) {
			if (!"".equals(status)) {
				if ("0".equals(status)) {
					if ("0".equals(webGoods.getFailReason()) && !webGoods.getCnName().equals(goodsName)) {
						list.add(webGoods);
					}
				} else {
					if (!webGoods.getCnName().equals(goodsName) && !"0".equals(webGoods.getFailReason())) {
						list.add(webGoods);
					}
				}
			} else {
				if (!webGoods.getCnName().equals(goodsName)) {
					list.add(webGoods);
				}
			}
		}
		for (WebGoods webGoods : list0) {
			if (!webGoods.getCnName().equals(goodsName)) {
				list1.add(webGoods);
			}
		}
		if ("2".equals(yongUser.getUserType())) {
			model.addAttribute("fastStore", webStoreService.findStoreByUserId(WebUserUtils.getYongUser().getId()));
		} else {
			model.addAttribute("fastStore", webStoreService.storeList());
		}
		model.addAttribute("list", list);
		model.addAttribute("failureNum", failureNum);
		model.addAttribute("orderLength", orderLength);
		model.addAttribute("ords", 1);
		model.addAttribute("status", status);
		session.setAttribute("orderList", list1);
		session.setAttribute("importList", list);
		model.addAttribute("storeCode", storeCode);
		return "modules/web/Order/fastOrder";
	}

	// 快速下单导出
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/exportOrders")
	public void exportOrders(HttpSession session, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		List<WebGoods> list0;
		if ((List<WebGoods>) session.getAttribute("importList") == null) {
			list0 = (List<WebGoods>) session.getAttribute("orderList");
		} else {
			list0 = (List<WebGoods>) session.getAttribute("importList");
		}
		List<WebExportOrder> list = new ArrayList<WebExportOrder>();
		for (int i = 0; i < list0.size(); i++) {
			WebExportOrder exports = new WebExportOrder();
			if ("0".equals(list0.get(i).getFailReason())) {
				exports.setFailReason("成功");
			} else if ("1".equals(list0.get(i).getFailReason())) {
				exports.setFailReason("配件编号匹配失败");
			} else if ("2".equals(list0.get(i).getFailReason())) {
				exports.setFailReason("商品名称匹配失败");
			} else {
				exports.setFailReason("商品配件与编号不一致");
			}
			exports.setGoodsName(list0.get(i).getCnName());
			exports.setPartsCode(list0.get(i).getPartsCode());
			exports.setGoodsNum(list0.get(i).getGoodsNum());
			list.add(exports);
		}
		String fileName = "快速下单匹配" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
		new ExportExcel("极配正品快速下单匹配结果", WebExportOrder.class).setDataList(list).write(response, fileName).dispose();

	}

	// 个人可用信用额度
	@ResponseBody
	@RequestMapping(value = "kYong")
	public Map<String, Object> kYong(String id) {
		Map<String, Object> map = new HashMap<String, Object>();
		WebCredit credit = webCreditService.selectByUserId(Integer.parseInt(id));
		if (credit != null) {
			map.put("kyong", (credit.getMoney().add(credit.getRechargeMoney())).subtract(credit.getUseMoney()));
		} else {
			map.put("kyong", 0);
		}
		return map;
	}

	// 快速下单结算
	@RequestMapping(value = "vipfastOrder")
	public String vipfastOrder(String receiveAreaId, String isFree, String transportType, Integer[] goodsNum,
			String[] goodsId, String[] goodsName, Double[] goodPrice, String userId, String storeCode,
			String buyStoreName, String[] partsCode, HttpSession session, RedirectAttributes redirectAttributes) {
		Double totalMoney = 0.0;
		for (int i = 0; i < goodsId.length; i++) {
			totalMoney = totalMoney + goodPrice[i] * goodsNum[i];
		}
		// 信用额度调整
		String code = getOrderReturnCode();
		WebYongUser yongUser = WebUserUtils.getYongUser();

		WebCredit credit = new WebCredit();
		WebCredit cr = webCreditService.selectByUserId(Integer.parseInt(yongUser.getId()));
		if ("1".equals(transportType)) {
			credit.setUseMoney(cr.getUseMoney().add(BigDecimal.valueOf(totalMoney * 1.1)));
		} else {
			credit.setUseMoney(cr.getUseMoney().add(BigDecimal.valueOf(totalMoney)));
		}
		credit.setUserId(Integer.parseInt(yongUser.getId()));
		credit.setUpdateDate(new Date());
		webCreditService.updateUseMoney(credit);

		WebAddress addr = webAddressService.selectByAddressId(receiveAreaId);
		WebOrders order = new WebOrders();
		if (yongUser.getBeStoreCode().equals(storeCode)) {
			order.setSysUserId(yongUser.getBeSysUserId());
		}
		order.setMoney(BigDecimal.valueOf(totalMoney));
		if ("1".equals(transportType)) {
			Double TotalMone = totalMoney * 1.1;
			order.setPayMoney(BigDecimal.valueOf(TotalMone));
			order.setFreight(BigDecimal.valueOf(totalMoney * 0.1));
		} else {
			order.setPayMoney(BigDecimal.valueOf(totalMoney));
		}
		if (addr != null) {
			order.setReceiveAddress(addr.getAddress());
			order.setReceivePhone(addr.getPhone());
			order.setReceiveName(yongUser.getLoginName());
		}
		order.setOrderType(3);
		order.setTransportType(transportType);
		order.setUserId(Integer.parseInt(yongUser.getId()));
		order.setBuyStoreCode(storeCode);

		order.setBuyStoreName(buyStoreName);
		order.setCreateDate(new Date());
		order.setUpdateDate(new Date());
		order.setCreateBy(yongUser);
		order.setUpdateBy(yongUser);
		order.setCode(code);
		order.setIsHistory("0");
		order.setState("2");
		order.setPayType("0");
		orderService.save(order);
		for (int i = 0; i < goodsId.length; i++) {
			WebOrdersDetail ordersDetail = new WebOrdersDetail();
			WebGoods goods = webGoodsService.get(goodsId[i]);
			ordersDetail.setOrdersCode(code);
			ordersDetail.setGoodsCnName(goods.getCnName());
			ordersDetail.setGoodsCode(goods.getGoodsCode());
			ordersDetail.setNum(goodsNum[i]);
			ordersDetail.setPrice(BigDecimal.valueOf(goodPrice[i]));
			ordersDetail.setIsHistroy("0");
			ordersDetail.setPartsCode(partsCode[i]);
			ordersDetail.setCreateDate(new Date());
			ordersDetail.setCreateBy(yongUser);
			webOrdersDetailService.save(ordersDetail);
		}

		return "redirect:" + Global.getFrontPath() + "/order/myOrder";
	}

	public String getOrderReturnCode() {
		String format = "%02d";
		Date nowDate = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String now = sdf.format(nowDate);
		int orderCode = getMaxOrderReturnCode(now);
		orderCode = orderCode + 1;
		String a = now + format;
		return String.format(a, orderCode);
	}

	private int getMaxOrderReturnCode(String now) {
		String code = orderService.findMaxCode(now);
		if (code != null) {
			return Integer.parseInt(code.substring(14));
		} else {
			return 0;
		}
	}

}